package cn.krund.lyc.hotlerobot.Ros.service.communication;

import android.os.Looper;

import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * @包名: cn.krund.lyc.hotlerobot.robot.service.communication
 * @作者: 刘育成
 * @时间: 2018/4/5  14:19
 * @org: 克路德人工智能
 * @描述: TODO
 * @fileName: CommunicationRunnable
 */

public abstract class CommunicationRunnable implements Runnable {

    protected Socket m_socket;                                      // 当前的socket
    protected static List<Socket> phoneSockets;                          // socket连接的列表
    protected static Socket RosSocket;                              // Ros的socket

    private IRosCommunicationListener mCommunicationListener;

    public CommunicationRunnable(Socket socket, IRosCommunicationListener communicationListener) {
        this.m_socket = socket;
        if (phoneSockets == null) {
            phoneSockets = new ArrayList<>();
        }
        this.mCommunicationListener = communicationListener;
    }

    protected abstract void socketHandler(Socket socket) throws Exception;

    @Override
    public void run() {
        try {
            socketHandler(m_socket);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (m_socket != null) {
                try {
                    if (mCommunicationListener != null && m_socket.isConnected()) {
                        mCommunicationListener.onDisconnect(m_socket.getInetAddress().getHostAddress(), m_socket.getPort());
                    }
                    phoneSockets.remove(m_socket);
                    m_socket.close();
                    m_socket = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
